package com.hyjy.music.base

import android.app.Dialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.ParameterizedType

/**
 * DialogFragment基类
 */
abstract class BaseDialogFragment<VB : ViewBinding> : DialogFragment() {
    protected var binding: VB? = null

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return initDialog()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        initViewBinding(inflater)
        return binding?.root
    }

    private fun initViewBinding(inflater: LayoutInflater) {
        val type = javaClass.genericSuperclass as ParameterizedType
        try {
            val cls = type.actualTypeArguments[0] as Class<*>
            val method = cls.getDeclaredMethod("inflate", LayoutInflater::class.java)
            binding = method.invoke(null, inflater) as? VB
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        }
    }

    override fun onStart() {
        super.onStart()
        // 设置对话框全屏显示
        dialog?.window?.let {
            val dm = resources.displayMetrics
            val width = dm.widthPixels
            val height = dm.heightPixels
            Log.i("BaseDialogFragment", "width = $width")
            Log.i("BaseDialogFragment", "height = $height")
            it.setLayout(width, it.attributes.height)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
    }

    protected abstract fun initDialog(): Dialog

    protected abstract fun initData()
}